package com.appium.manager.element;

import com.appium.manager.data.TestDataHandler;
import io.appium.java_client.android.AndroidDriver;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebElement;

import java.io.FileNotFoundException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 大忽悠
 * @create 2022/7/8 14:57
 */
@Slf4j
public abstract class AbstractElement {
    /**
     * 驱动
     */
    protected AndroidDriver<WebElement> androidDriver;

    /**
     * 默认会使用appiumTestData.yml作为测试数据文件
     */
    protected TestDataHandler testDataHandler;

    protected Method curTestMethod;

    protected Map<Method,Integer> testDataRegistry=new ConcurrentHashMap<>();


    /**
     * 写入一个测试数据
     */
    public void write(WebElement webElement) throws FileNotFoundException {
        if(curTestMethod==null){
            throw new RuntimeException("请先设置当前正在执行的测试方法");
        }
        Integer testDataIndex = testDataRegistry.get(curTestMethod);
        String data = testDataHandler.getTestDataByIndex(curTestMethod, testDataIndex);
        log.info("当前方法为: {},当前输入的测试数据为: {}, 当前测试数据索引为: {}, 要输入的元素为: {}"
                ,curTestMethod.getName(),data,testDataIndex,webElement);
        webElement.sendKeys(data);
        testDataRegistry.put(curTestMethod,testDataIndex+1);
    }


    /**
     * 单位是毫秒
     */
    public void waitWhile(int waitTime) throws InterruptedException {
        Thread.sleep(waitTime);
    }

    /**
     * 默认等3秒
     */
    public void waitWhile() throws InterruptedException {
        Thread.sleep(3*1000);
    }


    public AndroidDriver<WebElement> getAndroidDriver(){
        return androidDriver;
    }

    public void setTestMethod(Method testMethod) {
        curTestMethod=testMethod;
        log.info("设置当前测试方法为 {}",testMethod.getName());
        if(!testDataRegistry.containsKey(testMethod)){
            log.info("当前测试方法第一次被保存,测试数据索引初值被设置为0");
            testDataRegistry.put(testMethod,0);
        }
    }
}
